package cn.sibu.myroot.actionbar;

import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.PopupMenu;

import cn.sibu.myroot.R;

public class OptionsActivity extends AppCompatActivity implements PopupMenu.OnMenuItemClickListener,CompoundButton.OnCheckedChangeListener {

    private MenuItem mOpptionsItem;
    private CheckBox mFirstOption,mSecondOption;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.options, menu);
        //查找并初始化动作项
        mOpptionsItem = menu.findItem(R.id.menu_add);
        MenuItemCompat.setOnActionExpandListener(mOpptionsItem, new MenuItemCompat.OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionExpand(MenuItem item) {
                //必须返回true以使项展开
                return true;
            }

            @Override
            public boolean onMenuItemActionCollapse(MenuItem item) {
                mFirstOption.setChecked(false);
                mSecondOption.setChecked(false);
                //必须返回true以使项展开
                return true;
            }
        });
        Log.e("mOpptionsItem",""+mOpptionsItem);
        mFirstOption = (CheckBox) MenuItemCompat.getActionView(mOpptionsItem).findViewById(R.id.option_first);
        mSecondOption = (CheckBox) MenuItemCompat.getActionView(mOpptionsItem).findViewById(R.id.option_second);
        mFirstOption.setOnCheckedChangeListener(this);
        mSecondOption.setOnCheckedChangeListener(this);
        return true;
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            if(mFirstOption.isChecked()&&mSecondOption.isChecked()){
                //隐藏动作视图
                MenuItemCompat.collapseActionView(mOpptionsItem);
            }
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        menuItemSelected(item);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        //使用此回调执行每次菜单打开时需要调用的设置
        return super.onPrepareOptionsMenu(menu);
    }

    //通过标准选项菜单点击回调
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        menuItemSelected(item);
        return true;
    }
    private void menuItemSelected(MenuItem item){
        //按id获得选择的选项
        switch (item.getItemId()){
            case R.id.menu_add:
                break;
            case R.id.menu_remove:
                break;
            case R.id.menu_edit:
                break;
            case R.id.menu_setting:
                break;
            default:
                break;
        }
    }
}
